package com.cl.code.database.mybatis.module.sql.condition;

import com.cl.code.database.mybatis.module.sql.operator.LogicSqlOperator;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chengliang
 * @since 1.0.0
 */
public class CombinationConditionItem extends ConditionItem {

    private final List<ConditionItem> items;

    public CombinationConditionItem(LogicSqlOperator andOr, List<ConditionItem> items) {
        super(andOr);
        this.items = items;
    }

    @Override
    public String getSql() {
        if (items.isEmpty()) {
            return "";
        }
        String sql = items.stream().map(ConditionItem::getSql).collect(Collectors.joining(" "));
        // 删除第一个逻辑运算符
        String innerFirstLogicSqlOperator = items.get(0).getAndOr().getOperator();
        int i = sql.indexOf(innerFirstLogicSqlOperator);
        if (i != -1) {
            sql = sql.substring(i + innerFirstLogicSqlOperator.length());
        }
        return super.andOr.getOperator() + " (" + sql + ")";
    }

}
